/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.perlak.filters.duplication;

import com.perlak.filesearch.FileSearchResult;
import com.perlak.filesearch.SingleFileResult;
import com.perlak.filters.FilteredItem;
import com.perlak.filters.IFilter;
import com.perlak.filters.IFilteredItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author mateusz
 */
public class DuplicationFilter implements IFilter {

    private List<IFilteredItem> filteredItems = new ArrayList<IFilteredItem>();
    private List<IFilteredItem> matchedItems = new ArrayList<IFilteredItem>();

    @Override
    public List<IFilteredItem> getFilteredFiles() {
        return filteredItems;
    }

    @Override
    public List<IFilteredItem> getMatchedFiles() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<IFilteredItem> filter(List<FileSearchResult> resultList) {
        Map<String, Duplication> duplicationMap = new HashMap<String, Duplication>();
        Map<String, SingleFileResult> fileMap = new HashMap<String, SingleFileResult>();

        for (FileSearchResult result : resultList) {
            for (SingleFileResult file : result.getFiles()) {
                String key = file.getFileHash(SingleFileResult.NORMAL_FILE_LEVEL);
                if (fileMap.containsKey(key)) { // we got duplication
                    Duplication dup = duplicationMap.get(key);
                    if (dup == null) {
                        dup = new Duplication();
                        duplicationMap.put(key, dup);
                    }
                    dup.AddDuplicatedFile(file);
                    matchedItems.add(dup);
                } else {
                    fileMap.put(key, file);
                    filteredItems.add(new FilteredItem(file));
                }
            }
        }
        return matchedItems;
    }

    @Override
    public String getName() {
        return this.getClass().getName();
    }
}
